<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button :icon="Warning" text>仅显示最近1个月</el-button>
      </template>
      <template #endTime="scope">
        <span v-if="scope.row.endTime">{{ timeRender(scope) }}</span>
        <el-button v-else type="primary" link @click="onEndRushjob(scope.row)"> 结束突击 </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button
          v-if="userUser.userInfo._id === scope.row.userId && scope.row.state === '0'"
          type="primary"
          link
          :icon="EditPen"
          @click="openDrawer('编辑', scope.row)"
          >编辑
        </el-button>
        <el-button
          v-if="userUser.userInfo._id === scope.row.userId && scope.row.state === '0'"
          type="primary"
          link
          :icon="Delete"
          @click="deleteAccount(scope.row)"
          >删除
        </el-button>
      </template>
    </ProTable>
    <ApplyDrawer ref="drawerRef" />
    <InfoDialog ref="infoRef"></InfoDialog>
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed, onMounted } from "vue";
import { RushJob } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ApplyDrawer from "./applyDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Warning } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { timeRender } from "@/hooks/useColumnRender";
import { useUserStore } from "@/stores/modules/user";
import InfoDialog from "@/layouts/components/Header/components/InfoDialog.vue";
import { userRender } from "@/hooks/useColumnRender";
import { useDataStore } from "@/stores/modules/data";
import { calculateOvertimeHours } from "@/utils";

const initVar = reactive({
  tbName: "rushJobs",
  tbCnName: "突击"
});

// ProTable 实例
const proTable = ref<ProTableInstance>();
const userUser = useUserStore();
const dataStore = useDataStore();

const userList = computed(() => dataStore.userList);
onMounted(async () => {
  dataStore.findUserList();
});

let curDate = new Date();
let t = new Date(curDate.getFullYear(), curDate.getMonth() - 1, curDate.getDate(), 0, 0, 0);
let e = new Date(curDate.getFullYear(), curDate.getMonth(), curDate.getDate(), 23, 59, 59);
const initParam = reactive({
  condition: { userId: userUser.userInfo._id, startTime: { $gte: t, $lte: e } },
  options: { sort: { startTime: -1 } }
});

const getTableList = (params: any) => {
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

// 表格配置项
const columns = reactive<ColumnProps<RushJob>[]>([
  { type: "index", label: "序号", width: 85 },
  { prop: "userName", label: "姓名", width: 120 },
  { prop: "workNo", label: "工号", width: 120 },
  { prop: "workNote", label: "突击内容", align: "left", search: { el: "input", like: true } },
  { prop: "startTime", label: "开始时间", width: 180, render: timeRender },
  {
    prop: "endTime",
    label: "结束时间",
    width: 180
  },
  { prop: "workTime", label: "突击时间(小时)", width: 140 },
  {
    prop: "isHoliday",
    label: "节假日",
    width: 120,
    enum: () => apiService.findClassify("IS_NOT"),
    fieldNames: { label: "name", value: "value" }
  },
  {
    prop: "charge_user",
    label: "审核人",
    width: 120,
    render: scope => userRender(scope, userList)
  },
  {
    prop: "state",
    label: "状态",
    width: 120,
    enum: () => apiService.findClassify("APPROVAL_STATE"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "operation", label: "操作", align: "left", fixed: "right", width: 240 }
]);

// 删除信息
const deleteAccount = async (params: RushJob) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ApplyDrawer> | null>(null);
const infoRef = ref<InstanceType<typeof InfoDialog> | null>(null);
const openDrawer = (title: string, row: Partial<RushJob> = {}) => {
  if (userUser.userInfo.workNo) {
    const params = {
      title,
      tbName: initVar.tbName,
      isView: title === "查看",
      row: row,
      api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
      getTableList: proTable.value?.getTableList
    };
    drawerRef.value?.acceptParams(params);
  } else {
    infoRef.value?.openDialog();
  }
};

const onEndRushjob = async row => {
  let curDate = new Date();
  let workTime = calculateOvertimeHours(row.startTime, row.endTime);
  row.endTime = curDate;
  row.workTime = workTime;
  useHandleData(apiService.updateById, initVar.tbName, { _id: row._id, endTime: curDate, workTime: workTime }, "结束突击").catch(
    () => {
      delete row.endTime;
      delete row.workTime;
    }
  );
};
</script>
